from fastapi import FastAPI, Depends, Request
from fastapi.responses import JSONResponse
from uvicorn import run


class DBError(Exception):
    pass


class Session:
    def commit(self):
        print("数据库commit")

    def rollback(self):
        print("数据库正在回滚")

    def close(self):
        print("数据库连接正在关闭")

    def make_error(self):
        raise DBError("我要制造一个错误")

    def get(self):
        print("这是一个正常的操作")


def get_db() -> Session:
    session = Session()
    try:
        yield session
    except Exception as e:
        print(e)
        session.rollback()
        raise
    else:
        session.commit()
    finally:
        session.close()


def db_error_handler(_: Request, exc: DBError):
    print(f"数据库错误  {exc}")
    return JSONResponse({"msg": "数据库发生了错误"}, status_code=500)


def other_error(_: Request, exc: DBError):
    print(f"未知错误  {exc}")
    return JSONResponse({"msg": "未知错误"}, status_code=500)


app = FastAPI()

app.add_exception_handler(DBError, db_error_handler)
app.add_exception_handler(ZeroDivisionError, other_error)


@app.get("/get")
def hi(db: Session = Depends(get_db)):
    db.get()
    return "get"


@app.get("/error")
def hi(db: Session = Depends(get_db)):
    1 / 0
    db.make_error()
    return "hi"


if __name__ == '__main__':
    run(app)
